<template>
  <el-container style="height: 100%" class="el-container">
    <div class="header">
      <!-- <div class="affix-container">
        <el-affix position="bottom" :offset="180">
          <el-button @click="show = !show" style="border: 0" circle>
            <div ref="lottieContainer" class="lottie-container"></div>
          </el-button>
        </el-affix>
      </div> -->
      <el-button @click="saveResult" class="gradient-border-btn save-btn">
        <i class="fa fa-save mr-2"></i>保存分析结果
      </el-button>
      <el-button @click="exportResult" class="gradient-border-btn export-btn">
        <i class="fa fa-download mr-2"></i>导出分析结果
      </el-button>
      <div class="title" v-if="titleFlag">{{ title }}</div>
      <div class="bouncing-dot-animation" v-if="titleFlag">
        <div class="dot"></div>
        <div class="dot"></div>
        <div class="dot"></div>
        <div class="dot"></div>
      </div>
    </div>
    <footer>
      <!-- 添加过渡动画 -->
      <transition
        name="fade"
        @before-enter="beforeEnter"
        @enter="enter"
        @leave="leave"
      >
        <el-aside
          v-if="show"
          width="255px"
          style="height: 100%; padding: 10px"
          class="affix-container-aside"
        >
          <el-menu style="height: 100%" :default-openeds="['8']">
            <div
              style="
                font-size: 1.1rem;
                font-weight: 550;
                text-align: left;
                padding: 0 1rem;
                margin-bottom: 10px;
              "
              class="menu-title"
            >
              <div>目 录</div>
              <div style="margin-top: 5px">
                <el-tag type="danger" style="color: red">未填写数量</el-tag>
                <el-tag type="danger" style="margin-left: 5px; color: green"
                  >已填写完成</el-tag
                >
              </div>
            </div>

            <template v-for="(menu, idx) in menuLst" :key="menu.key">
              <el-menu-item :index="menu.key" @click="clickMenu(idx)">
                <template #title>
                  <el-badge
                    :value="menu.value == 0 ? '√' : menu.value"
                    class="custom-badge"
                    :color="menu.value == 0 ? 'green' : 'red'"
                    :is-dot="menu.value == 0"
                  >
                    <span class="badge-content">{{ menu.title }}</span>
                  </el-badge>
                </template>
              </el-menu-item>
            </template>
            <el-sub-menu index="8" :collapse="true">
              <template #title>
                <el-badge
                  :value="tierNum == 0 ? '' : tierNum"
                  class="custom-badge"
                  :color="tierNum == 0 ? 'green' : 'red'"
                >
                  <span class="badge-content">档次信息</span>
                </el-badge>
              </template>
              <template v-if="tierLst.length === 0">
                <el-menu-item index="8-1" disabled>
                  <div ref="lottieCar" class="lottie-car"></div>
                </el-menu-item>
              </template>
              <template v-else>
                <el-menu-item
                  v-for="item in tierLst"
                  :index="item.index"
                  :key="item.key"
                  @click="showTier(item.index)"
                >
                  <template #title>{{ item.title }}</template>
                </el-menu-item>
              </template>
            </el-sub-menu>
          </el-menu>
        </el-aside>
      </transition>
      <keep-alive>
        <el-main class="affix-container-main">
          <component
            :is="contentComp.component"
            :result="result"
            :changeTierLst="changeTierLst"
          />
        </el-main>
      </keep-alive>
    </footer>
  </el-container>
</template>
<script setup>
import {
  onMounted,
  reactive,
  ref,
  shallowRef,
  toRaw,
  nextTick,
  watch,
} from "vue";
import BasicInfo from "@/views/BasicInfo.vue";
import ProductInfo from "@/views/ProductInfo.vue";
import RulesInfo from "@/views/RulesInfo.vue";
import ContractInfo from "@/views/ContractInfo.vue";
import ReminderInfo from "@/views/ReminderInfo.vue";
import ConfirmationPage from "@/views/ConfirmationPage.vue";
import CostPage from "@/views/CostPage.vue";
import OtherPage from "@/views/OtherPage.vue";
import TierPage from "@/views/TierPage.vue";
import SubPage from "@/views/SubPage.vue";
import axios from "axios";
import { ElMessageBox, ElMessage } from "element-plus";
import { useStore } from "vuex"; // 引入 useStore
import router from "@/router";
import lottie from "lottie-web";
import {
  createDic,
  mapping0,
  mapping1,
  mapping2,
  mapping3,
  mapping4,
  mapping5,
  mapping6,
  mapping7,
  mapping8,
  mapping9,
} from "./config.js";
import { getForms } from "@/api/index.js";
import downloadUtil from "@/api/downloadUtil.js";

const store = useStore(); // 获取 store 实例
const mapping = {
  mapping0,
  mapping1,
  mapping2,
  mapping3,
  mapping4,
  mapping5,
  mapping6,
  mapping7,
  mapping8,
};
const menuLst = reactive([
  {
    key: "BasicInfo",
    title: "基本信息",
    value: "0",
    component: shallowRef(BasicInfo),
    index: 0,
  },
  {
    key: "RulesInfo",
    title: "生/失效规则",
    value: "0",
    component: shallowRef(RulesInfo),
    index: 1,
  },
  {
    key: "ProductInfo",
    title: "关联产品信息",
    value: "0",
    component: shallowRef(ProductInfo),
    index: 2,
  },
  {
    key: "ContractInfo",
    title: "合约信息",
    value: "0",
    component: shallowRef(ContractInfo),
    index: 3,
  },
  {
    key: "SubPage",
    title: "客服信息-订阅提醒",
    value: "0",
    component: shallowRef(SubPage),
    index: 4,
  },
  {
    key: "Reminder",
    title: "客服信息-到期提醒",
    value: "0",
    component: shallowRef(ReminderInfo),
    index: 5,
  },
  {
    key: "Confirmation",
    title: "客服信息-短信订购二次确认",
    value: "0",
    component: shallowRef(ConfirmationPage),
    index: 6,
  },
  {
    key: "Cost",
    value: "0",
    title: "渠道费用结算信息",
    component: shallowRef(CostPage),
    index: 7,
  },
  {
    key: "Other",
    title: "其他信息",
    value: "0",
    component: shallowRef(OtherPage),
    index: 8,
  },
]);
let tierLst = reactive([]); // 档次的数据
const tierNum = ref(0);
const titleFlag = ref(false);
const title = ref("正在摘要信息提取");
const titleName = ref([
  "正在摘要信息提取",
  "正在档次信息拆分",
  "正在档次内容解析",
  "正在信息整合",
  "正在数据校验处理",
  "正在优化数据结构",
  "正在归档处理记录",
  "正在清理临时数据",
  "正在更新系统日志",
  "正在执行性能优化",
  "正在执行最终审核",
  "正在完成最终交付",
  "正在准备输出结果",
]);

let i = 0;
const intervalId = ref(null);

// 生成1500-4000ms之间的随机延迟
const getRandomDelay = () =>
  Math.floor(Math.random() * (4000 - 1500 + 1)) + 1500;

// 带随机延迟的标题切换函数
const changeTitleWithRandomDelay = () => {
  title.value = titleName.value[i];

  if (i < titleName.value.length - 1) {
    i++;
  } else {
    clearInterval(intervalId.value);
    return;
  }

  // 清除上一个定时器
  clearInterval(intervalId.value);

  // 设置新的随机延迟定时器
  intervalId.value = setTimeout(changeTitleWithRandomDelay, getRandomDelay());
};

// 监听表单控件 控制badge显示
watch(
  () => store.state.basicInfo.data,
  (newVal) => {
    if (!Array.isArray(newVal)) return;
    const allMatches = newVal.filter((item) => item.tagName === "工号组选择"); //
    console.log("判断服务端是否返回", allMatches);

    menuLst.forEach((item) => {
      const tagsToMatch = mapping[`mapping${item.index}`] || [];
      const result = newVal.filter(
        (jtem) =>
          tagsToMatch.includes(jtem.tagName) &&
          (jtem.tagValue == null ||
            jtem.tagValue == "" ||
            jtem.tagValue == undefined ||
            Array.isArray(jtem.tagValue))
      );
      const i = result.length;
      item.value = i;
    });
    console.log("menuLst", menuLst);
  },
  {
    deep: true,
    immediate: true,
  }
);

// 监听档次数据 控制badge显示
watch(
  () => tierLst,
  (val) => {
    console.log("监听档次数据", val);
    const result1 = val.flatMap((item) => {
      return item.data?.value || []; // 确保 value 存在且是数组
    });
    console.log("result1", result1);
    tierNum.value = result1.filter((item) => {
      return (
        mapping9.includes(item.tagName) &&
        (item.tagValue === "" ||
          item.tagValue === null ||
          item.tagValue === undefined)
      );
    }).length;
    console.log("tierNum", tierNum.value);
  },
  { deep: true, immediate: true }
);

const lottieContainer = ref(null);
const lottieCar = ref(null);

const animationfn = () => {
  lottie.loadAnimation({
    container: lottieContainer.value, // 指定渲染容器
    renderer: "svg", // 渲染方式：svg, canvas, html
    loop: true, // 是否循环播放
    autoplay: true, // 是否自动播放
    animationData: require("@/assets/svg/animation.json"), // 使用你的动画 JSON 文件
  });

  lottie.loadAnimation({
    container: lottieCar.value, // 指定渲染容器
    renderer: "svg", // 渲染方式：svg, canvas, html
    loop: true, // 是否循环播放
    autoplay: true, // 是否自动播放
    animationData: require("@/assets/svg/car-loading2-data.json"), // 使用你的动画 JSON 文件
  });
};

const show = ref(true);

const contentComp = reactive({
  component: undefined,
});

const clickMenu = (idx) => {
  contentComp.component = menuLst[idx].component;
};
const result = ref({});

const showTier = (idx) => {
  contentComp.component = shallowRef(TierPage);
  result.value = toRaw(
    tierLst.find((item) => {
      return item.key === idx;
    }).data
  );
};

const changeTierLst = (obj) => {
  if (!obj.flag) {
    tierLst.forEach((item) => {
      if (item.title === obj.name) {
        const res = JSON.parse(JSON.stringify(item.data.value));
        res.forEach((jtem) => {
          if (jtem.tagName === obj.label) {
            jtem.tagValue = obj.value;
          }
        });
        item.data = { name: item.title, value: res };
      }
    });
    return;
  }

  tierLst.forEach((item) => {
    const res = item.data.value;
    res.forEach((jtem) => {
      if (jtem.tagName === obj.label) {
        jtem.tagValue = obj.value;
      }
    });
    item.data = { name: item.title, value: res };
  });
  ElMessage({
    message: "应用成功",
    type: "success",
  });
};

const send_request = () => {
  const selected = store.getters.getTemplate;
  const input_txt = store.getters.getInputTxt;

  if (
    !selected ||
    !input_txt ||
    selected === null ||
    input_txt === null ||
    selected === "" ||
    input_txt === ""
  ) {
    ElMessageBox.confirm(
      "未收到用户输入，请从首页开始，点击‘确定’按钮跳转到首页",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    )
      .then(() => {
        router.push("/input");
      })
      .catch(() => {});
    return;
  }

  axios({
    method: "post",
    url: "/api/text/analyze",
    data: {
      templateName: selected,
      text: input_txt,
    },
  }).then((resp) => {
    const pre = [
      { tagCode: null, tagName: "档次编码", tagValue: "" },
      { tagCode: null, tagName: "账单显示名称", tagValue: null },
      { tagCode: null, tagName: "预存分摊", tagValue: null },
      { tagCode: null, tagName: "月保底", tagValue: null },
      { tagCode: null, tagName: "协议期", tagValue: null },
      { tagCode: null, tagName: "协议期是否积分", tagValue: null },
      { tagCode: null, tagName: "是否允许0000查询退订", tagValue: null },
      { tagCode: null, tagName: "违约金金额", tagValue: "" },
    ];
    for (let item in resp.data.data) {
      resp.data.data[item] = [...pre, ...resp.data.data[item]];
    }
    const analyzeResult = resp.data;
    console.log("analyzeResult", analyzeResult);
    const name = analyzeResult.data["档次1"][8]["tagValue"] || "";
    console.log("name", name);
    store.commit("setBasicInfo", {
      data: [
        ...store.state.basicInfo.data,
        { tagCode: "prodName", tagName: "产品名称", tagValue: name },
      ],
      timestamp: new Date().getTime(),
    });
    clearInterval(intervalId);
    titleFlag.value = false;

    if (
      analyzeResult.code !== 200 ||
      Object.values(analyzeResult.data).length == 0
    ) {
      ElMessage.error(analyzeResult.msg);
      tierLst = [];
      return;
    } else {
      // console.log("result.value", result.value);
      // result.value["analyzeResult"] = analyzeResult.data;
      // result.value["timestamp"] = new Date().getTime();
      // console.log("result.value", result.value);
    }
    let entries = Object.entries(analyzeResult.data);

    entries.forEach(([key, value]) => {
      tierLst.push({
        key: key,
        index: `${key}`,
        title: key,
        data: {
          name: key,
          value: [...value],
        },
      });
    });
    // console.log("entries", entries);
  });

  axios({
    method: "post",
    url: "/api/text/basic-information-v1",
    data: {
      templateName: selected,
      text: input_txt,
    },
  }).then((resp) => {
    const baseInfo = resp.data;

    const deadData = [
      { tagCode: "资费归属", tagName: "资费归属", tagValue: "" },
      { tagCode: "是否网龄限制", tagName: "是否网龄限制", tagValue: "" },
      { tagCode: "电话", tagName: "电话", tagValue: "" },
      { tagCode: "邮箱", tagName: "邮箱", tagValue: "" },
      { tagCode: "违约金支付方式", tagName: "违约金支付方式", tagValue: "" },
      {
        tagCode: "是否使用标准模板",
        tagName: "是否使用标准模板",
        tagValue: "",
      },
      { tagCode: "地市", tagName: "地市", tagValue: "" },
      { tagCode: "开始时间", tagName: "开始时间", tagValue: "" },
      { tagCode: "截止时间", tagName: "截止时间", tagValue: "" },
      { tagCode: "提前几天提醒", tagName: "提前几天提醒", tagValue: "" },
      { tagCode: "短信下发时间", tagName: "短信下发时间", tagValue: "" },
      { tagCode: "是否业务拆分", tagName: "是否业务拆分", tagValue: "" },
      { tagCode: "是否新增账目", tagName: "是否新增账目", tagValue: "" },
    ];
    console.log("deadData", deadData);
    if (baseInfo.code !== 200) {
      ElMessage.error(baseInfo.msg);
      return;
    } else {
      store.commit("setBasicInfo", {
        data: [
          ...deadData,
          ...baseInfo.data,
          { tagCode: "prodName", tagName: "产品名称", tagValue: "" },
        ],
        timestamp: new Date().getTime(),
      });
    }
    // loading.close();
    contentComp.component = menuLst[0].component;
  });
};

const exportResult = () => {
  if (titleFlag.value) {
    ElMessage({
      message: "请等待摘要信息提取完成",
      type: "info",
    });
    return;
  }
  const num1 = menuLst.reduce((sum, pre) => sum + Number(pre.value), 0);
  if (num1 + Number(tierNum.value) != 0) {
    ElMessage({
      message: "请根据提示填写完整",
      type: "info",
    });
    return;
  }

  const res = store.state.basicInfo.data;
  const output = tierLst.reduce((acc, item) => {
    acc[item.title] = item.data.value;
    return acc;
  }, {});
  const prodId = res.find((item) => item.tagCode === "prodId")?.tagValue;
  const prodName = res.find((item) => item.tagCode === "prodName")?.tagValue;

  const result = {
    prodId: prodId,
    prodName: prodName,
    templateName: "营销资费申请模板（促销类）",
    baseInfo: res,
    gradeInfo: output,
  };
  getForms(JSON.stringify(result)).then((resp) => {
    downloadUtil.resultDownload(resp);
  });
};

onMounted(() => {
  nextTick(async () => {
    await createDic();
  });
  send_request();
  animationfn();
  titleFlag.value = true;
  changeTitleWithRandomDelay();
});
</script>
<style lang="less" scoped>
.affix-container {
  // transform: translate(10px, 10px);
  margin-right: 10px;
  .lottie-container {
    width: 50px;
    height: 50px;
    cursor: pointer;
    pointer-events: auto;
  }
}

/* 修复滚动条隐藏 */

:deep(.affix-container-aside, .el-container, .affix-container-main) {
  overflow: auto;
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE/Edge */

  &::-webkit-scrollbar {
    display: none; /* Chrome/Safari */
  }
}

/* 过渡动画定义 */
.fade-enter-active,
.fade-leave-active {
  transition: transform 0.3s ease, opacity 0.3s ease;
}

.fade-enter,
.fade-leave-to {
  transform: translateX(-100%);
  opacity: 0;
}

.el-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
  padding: 0 0 0 15px;

  .header {
    // width: 100%;
    background-color: #ffffff;
    padding: 12px 20px;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    border-radius: 10px;

    .title {
      margin-left: 20px;
      color: #606266;
      display: inline-block;
      margin-left: 8px;
      background: linear-gradient(90deg, #3498db, #9b59b6, #3498db);
      background-size: 200% auto;
      color: transparent;
      background-clip: text;
      -webkit-background-clip: text;
      animation: gradient 2s linear infinite;
    }

    @keyframes gradient {
      0% {
        background-position: 0% center;
      }
      100% {
        background-position: 200% center;
      }
    }

    .bouncing-dot-animation {
      display: inline-flex;
      margin: 0 3px;
      transform: translateY(4px);
    }

    .dot {
      width: 5px;
      height: 5px;
      background: linear-gradient(90deg, #3498db, #9b59b6, #3498db);
      border-radius: 50%;
      margin: 0 3px;
      animation: bounce 1.6s infinite ease-in-out;
      transform-origin: center bottom;
    }

    .dot:nth-child(1) {
      animation-delay: 0s;
    }
    .dot:nth-child(2) {
      animation-delay: 0.4s;
    }
    .dot:nth-child(3) {
      animation-delay: 0.8s;
    }
    .dot:nth-child(4) {
      animation-delay: 1.2s;
    }

    @keyframes bounce {
      0%,
      20%,
      100% {
        transform: translateY(0);
      }
      10% {
        transform: translateY(-10px);
      }
    }

    .gradient-border-btn {
      position: relative;
      background: transparent;
      border: none;
      padding: 10px 20px;
      font-size: 14px;
      font-weight: 500;
      cursor: pointer;
      margin-right: 15px;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      transition: all 0.3s ease;
      border-radius: 6px;
      z-index: 1;
    }

    /* 保存按钮渐变边框 */
    .save-btn::before {
      content: "";
      position: absolute;
      inset: -2px;
      border-radius: 8px;
      background: linear-gradient(135deg, #3498db, #9b59b6, #3498db);
      background-size: 200% 200%;
      animation: gradientBorder 3s ease infinite;
      z-index: -1;
    }

    /* 导出按钮渐变边框 */
    .export-btn::before {
      content: "";
      position: absolute;
      inset: -2px;
      border-radius: 8px;
      background: linear-gradient(135deg, #2ecc71, #e74c3c, #2ecc71);
      background-size: 200% 200%;
      animation: gradientBorder 3s ease infinite;
      z-index: -1;
    }

    /* 按钮内部背景 */
    .gradient-border-btn::after {
      content: "";
      position: absolute;
      inset: 0;
      background: white;
      border-radius: 6px;
      z-index: -1;
      transition: all 0.3s ease;
    }

    /* 保存按钮文字颜色 */
    .save-btn {
      color: #2980b9;
    }

    /* 导出按钮文字颜色 */
    .export-btn {
      color: #27ae60;
    }

    /* 悬停效果 */
    .gradient-border-btn:hover::after {
      background: rgba(255, 255, 255, 0.9);
    }

    .gradient-border-btn:hover {
      transform: translateY(-2px);
    }

    .gradient-border-btn:active {
      transform: translateY(1px);
    }

    /* 渐变动画 */
    @keyframes gradientBorder {
      0% {
        background-position: 0% 50%;
      }
      50% {
        background-position: 100% 50%;
      }
      100% {
        background-position: 0% 50%;
      }
    }

    /* 图标样式 */
    .gradient-border-btn i {
      margin-right: 8px;
      transition: transform 0.3s ease;
    }

    .gradient-border-btn:hover i {
      transform: translateX(-2px);
    }
  }

  footer {
    display: flex;
    margin: 15px 0 0 0;
    padding: 10px;
    border-radius: 10px;
    background-color: white;
    overflow: hidden;

    &::-webkit-scrollbar {
      display: none; /* Chrome/Safari */
    }
  }

  .lottie-car {
    width: 110px;
    height: 110px;
  }
  .affix-container-main {
    margin-top: -10px;
  }
}

.custom-badge {
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  align-items: center;
  gap: 4px;
  text-align: left;
}

/* 调整徽标位置 */
.custom-badge :deep(.el-badge__content) {
  position: relative;
  transform: none;
  margin: -41px -32px 0px 4px;
}
</style>
